//
//  SongListCtrl.swift
//  SwiftBase
//
//  Created by rubick on 2023/2/14.
//

import Foundation
import UIKit
import HandyJSON
import Kingfisher
import ZKProgressHUD

class SongListCtrl: RKBaseCtrl, RKActivityViewable {
    //
    var channelId: String?
    var showTitle: String?
    var tableView: UITableView!
    var songList: Array<SongModel?> = []
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        title = showTitle!
        setupView()
        requestData()
    }
    // 创建视图
    func setupView() {
        tableView = UITableView(frame: self.view.frame, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.register(SongInfoCell.self, forCellReuseIdentifier: "SongInfoCell")
        view.addSubview(tableView)
    }
    func requestData() {
        if (self.channelId != nil) {
            startAnimating(type: .ballClipRotateMultiple)
            HJNetworkRequest(DouBanApi.playlist("\(self.channelId!)")) { result in
                self.stopAnimating()
                let songArr = result["song"] as! Array<Any>
                if let resMode = [SongModel].deserialize(from: songArr) {
                    self.songList = resMode
                    self.tableView.reloadData()
                }
            } failed: { errorMsg, error in
                self.stopAnimating()
                ZKProgressHUD.showMessage(errorMsg)
            }
        }
    }
}
extension SongListCtrl: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.songList.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: SongInfoCell = tableView.dequeueReusableCell(withIdentifier: "SongInfoCell", for: indexPath) as! SongInfoCell
        cell.accessoryType = .disclosureIndicator
        let songModel = self.songList[indexPath.row]
        cell.songImageV?.kf.setImage(with: URL(string: (songModel?.picture)!), placeholder: UIImage(rk_color: UIColor.rk_random))
        cell.songTitleLab?.text = songModel?.title
        cell.songArtistLab?.text = songModel?.artist
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
